package com.ccx.coachsite;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ccx.coachsite.api.CoachSiteApiAccessor;
import com.ccx.coachsite.bus.Account;
import com.ccx.coachsite.bus.AccountMgr;
import com.ccx.coachsite.bus.MessageInfo;
import com.ccx.coachsite.bus.NoReadMessageInfo;
import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.data.SystemConst;
import com.ccx.coachsite.service.ShareMessageService;
import com.ccx.coachsite.ui.CommonAppView;
import com.ccx.coachsite.ui.custom.CustomMainView;
import com.ccx.coachsite.ui.login.LoginHelper;
import com.ccx.coachsite.ui.manage.ManageMainView;
import com.ccx.coachsite.ui.own.MyExpertView;
import com.ccx.coachsite.ui.own.OwerMainBase;
import com.ccx.coachsite.ui.own.OwerMainView;
import com.ccx.coachsite.ui.softmgr.SoftMgrTabLazyView;
import com.ccx.coachsite.ui.tutorial.TutorialList;
import com.ccx.coachsite.util.CrashTool;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.versionupdate.SoftUpdateService;

/**
 * 千站万员主框架
 * 
 * @author Cfb
 * 
 */
public class CoachSiteMainActivity extends Activity implements
		View.OnClickListener {

	public static final String TAG = "CoachSiteMainActivity";

	private boolean isExpert = false;
	private String lastUserId = "";

	public static final int defaultMark = -1;
	private FrameLayout contentFrame;
	private int currentMark = defaultMark;
	private LinkedHashMap<Integer, CommonAppView> viewCache = new LinkedHashMap<Integer, CommonAppView>();

	public CommonAppView comAppCustom;
	public CommonAppView comAppOwer;
	public MyExpertView comAppExpert;

	public static final int MAIN_VIEW = 1;
	public static final int APP_VIEW = 2;
	public static final int TUTORIAL_VIEW = 3;
	public static final int EXPERT_VIEW = 4;
	public static final int CLIENT_VIEW = 5;
	public static final int MANAGE_VIEW = 6;
	public static final int MORE_VIEW = 7;

	private RelativeLayout mainPageButton;
	private RelativeLayout appButton;
	private RelativeLayout tutorialButton;
	private RelativeLayout expertButton;
	private RelativeLayout clientButton;
	private RelativeLayout manageButton;
	private RelativeLayout moreButton;

	public static final String ACTION_SEARCH_NAME = "com.ccx.coachsite.SEARCH";
	public static final String ACTION_UPDATE_NEW_MESSAGE = "com.ccx.coachsite.UPDATE_NEW_MESSAGE";

	private SoftDownloadProgressReceiver mSoftDownloadProgressReceiver = new SoftDownloadProgressReceiver();

	public static boolean isOffLine = false;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 1)
				setNewMessageCount(msg.arg1, (String)msg.obj);
		}
	};

	// 两次按返回键退出程序
	private boolean isExit = false;
	private boolean hasTask = false;
	Timer tExit = new Timer();
	TimerTask exitTask = new TimerTask() {

		@Override
		public void run() {
			isExit = false;
			hasTask = true;
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		isExpert = SharedPreferencesUtil.getBoolean(this,
				SharedKey.Shared_Is_Expert);
		lastUserId = SharedPreferencesUtil.getValue(this,
				SharedKey.Shared_UserId_Key);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		SystemConst.createDefaultDir();

		CoachSiteApiAccessor.setAppContext(getApplicationContext());

		initContentFrame();

		// 判断网络情况
		if (!CrashTool.isNetworkAvailable(this)) {

			CrashTool.toastShow(this, R.string.hit_offline);
			CoachSiteMainActivity.isOffLine = true;

			// showChoosedView(CoachSiteMainActivity.MANAGE_VIEW);

			// return;
		}
		int page = getIntent().getIntExtra("SelectedPage", 2);
		showChoosedView(page);

		// 注册搜索广播
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(ACTION_SEARCH_NAME);
		registerReceiver(mBroadcastReceiver, myIntentFilter);

		// 异步请求是否有新版本可更新
		handler.postDelayed(new Runnable() {
			public void run() {
				startService(new Intent(CoachSiteMainActivity.this,
						SoftUpdateService.class));
			}

		}, 60000);

		// 异步请求是否有推送消息
		if (LoginHelper.isLogin(this)) {
			handler.postDelayed(new Runnable() {
				public void run() {
					startService(new Intent(CoachSiteMainActivity.this,
							ShareMessageService.class));
				}

			}, 10000);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(ACTION_UPDATE_NEW_MESSAGE);
		registerReceiver(new NewMessageReceiver(), myIntentFilter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		// 注销掉所有资源
		Iterator iter = viewCache.keySet().iterator();
		while (iter.hasNext()) {
			Object key = iter.next();
			CommonAppView commonAppView = viewCache.get(key);
			// 考虑遍历所有子View
			if (commonAppView != null)
				commonAppView.clearCache();
		}

		// this.unregisterReceiver( mSoftDownloadProgressReceiver );

		unregisterReceiver(mBroadcastReceiver);
	}

	@Override
	protected void onResume() {
		super.onResume();
		refreshMainMenu();
	}

	public void refreshMainMenu() {
		isExpert = SharedPreferencesUtil.getBoolean(this,
				SharedKey.Shared_Is_Expert);
		String userId = SharedPreferencesUtil.getValue(this,
				SharedKey.Shared_UserId_Key);
		if (!userId.equals(lastUserId)) {
			viewCache.remove(EXPERT_VIEW);
			viewCache.remove(MANAGE_VIEW);
			viewCache.remove(CLIENT_VIEW);
			lastUserId = userId;
		}
		if (isExpert) {
			this.moreButton.setVisibility(View.GONE);
			this.expertButton.setVisibility(View.GONE);
			this.clientButton.setVisibility(View.VISIBLE);
		} else {
			this.moreButton.setVisibility(View.GONE);
			this.expertButton.setVisibility(View.VISIBLE);
			this.clientButton.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		boolean newMessageFlag = intent.getBooleanExtra("noReadMessage", false);

		// NoReadMessageInfo noReadMessage = (NoReadMessageInfo) intent
		// .getSerializableExtra("noReadMessage");
		if (newMessageFlag) {
			if (!isExpert) {
				viewCache.remove(EXPERT_VIEW);
				showChoosedView(EXPERT_VIEW);
			} else {
				viewCache.remove(CLIENT_VIEW);
				showChoosedView(CLIENT_VIEW);
				CustomMainView cusView = (CustomMainView) comAppCustom;
				if (cusView != null) {
					cusView.enterCustomView();
					/*
					 * cusView.enterMessageView(noReadMessage.getLeaveMobile(),
					 * noReadMessage.getLeaveUser());
					 */
				}
			}
		}

		MessageInfo noSystemMessage = (MessageInfo) intent
				.getSerializableExtra("noSystemMessage");
		if (noSystemMessage != null) {
			if (isExpert) {
				viewCache.remove(MANAGE_VIEW);
				showChoosedView(MANAGE_VIEW);
			} else {
				viewCache.remove(CLIENT_VIEW);
				showChoosedView(CLIENT_VIEW);
			}

			OwerMainBase cusView = (OwerMainBase) comAppOwer;
			if (cusView != null) {
				cusView.EnterSystemMessageView(noSystemMessage);
			}
		}

	}

	private void initContentFrame() {

		setContentView(R.layout.coachsite_main);
		// isExpert = true;
		this.contentFrame = (FrameLayout) findViewById(R.id.contentFrame);

		this.mainPageButton = (RelativeLayout) findViewById(R.id.mainPageButton);
		this.appButton = (RelativeLayout) findViewById(R.id.appButton);
		this.tutorialButton = (RelativeLayout) findViewById(R.id.tutorialButton);
		this.expertButton = (RelativeLayout) findViewById(R.id.expertButton);
		this.manageButton = (RelativeLayout) findViewById(R.id.manageButton);
		this.moreButton = (RelativeLayout) findViewById(R.id.moreButton);
		this.clientButton = (RelativeLayout) findViewById(R.id.clientButton);
		if (isExpert) {
			this.moreButton.setVisibility(View.GONE);
		} else {
			this.clientButton.setVisibility(View.GONE);
		}
		registerView(CoachSiteMainActivity.MAIN_VIEW);
		registerView(CoachSiteMainActivity.APP_VIEW);
		registerView(CoachSiteMainActivity.TUTORIAL_VIEW);
		registerView(CoachSiteMainActivity.EXPERT_VIEW);
		registerView(CoachSiteMainActivity.CLIENT_VIEW);
		registerView(CoachSiteMainActivity.MANAGE_VIEW);
		registerView(CoachSiteMainActivity.MORE_VIEW);

		// registerTrigger(this.mainPageButton);
		this.mainPageButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		registerTrigger(this.appButton);
		registerTrigger(this.tutorialButton);
		registerTrigger(this.expertButton);
		registerTrigger(this.clientButton);
		registerTrigger(this.manageButton);
		registerTrigger(this.moreButton);

	}

	private final void registerView(int paramInt) {
		Integer localInteger = Integer.valueOf(paramInt);
		viewCache.put(localInteger, null);
	}

	private final void registerTrigger(View paramView) {
		paramView.setOnClickListener(this);
	}

	public void showChoosedView(int paramInt) {

		// 判断网络情况
		if (!CrashTool.isNetworkAvailable(this)) {
			// Toast提示网络异常
			CrashTool.toastShow(this, R.string.hit_network_problem);
		}

		Integer localInteger = Integer.valueOf(paramInt);
		CommonAppView localView = (CommonAppView) viewCache.get(localInteger);

		if (localView == null) {
			localView = createContentView(paramInt);
			if (paramInt != EXPERT_VIEW)
				viewCache.put(localInteger, localView);
		}

		onBeforeShowView(paramInt);

		CommonAppView currentView = getCurrentTab();
		if ((currentView == null) || (currentView != localView)) {
			currentMark = paramInt;
			contentFrame.removeAllViews();
			contentFrame.addView(localView);
		}

		if ((currentView != null) && (currentView == localView)) {
			currentView.flushView();
		}

		onAfterShowView(paramInt);
	}

	public void setNewMessageCount(int count, String users) {
		
		
			
		TextView txtCount = null;
		TextView txtCustomCount = null;
		
		SharedPreferencesUtil.setValue(CoachSiteMainActivity.this,
				SharedKey.Custom_Message_Count, String.valueOf(count));
		if (isExpert)
		{
			txtCount = (TextView) findViewById(R.id.txt_client_new_message_count);
			txtCustomCount = (TextView) findViewById(R.id.txt_custom_new_message_count);
			
			if(count > 0)
			{
				CustomMainView cusView = (CustomMainView) comAppCustom;
				if (cusView != null) 
					cusView.refreshMessage(users);
			}
			
		}
		else
		{
			if(count > 0)
			{
				if(comAppExpert != null)
					comAppExpert.loadMessages();
			}
			txtCount = (TextView) findViewById(R.id.txt_expert_new_message_count);
		}
		if (count <= 0)
		{
			if(txtCount != null)
				txtCount.setVisibility(View.INVISIBLE);
			
			if(txtCustomCount != null)
				txtCustomCount.setVisibility(View.INVISIBLE);
		}
		else {
			if(txtCount != null)
			{
				txtCount.setText(String.valueOf(count));
				txtCount.setVisibility(View.VISIBLE);
			}
			if(txtCustomCount != null)
			{
				txtCustomCount.setText(String.valueOf(count));
				txtCustomCount.setVisibility(View.VISIBLE);
			}
		}
	}

	private CommonAppView createContentView(int paramInt) {

		CommonAppView localObject = null;

		switch (paramInt) {
		// 首页
		case CoachSiteMainActivity.MAIN_VIEW:
			localObject = new CommonAppView(this);
			break;

		// 应用
		case CoachSiteMainActivity.APP_VIEW:
			localObject = new SoftMgrTabLazyView(this);
			break;

		// 教程
		case CoachSiteMainActivity.TUTORIAL_VIEW:
			// TODO 图片本地SD卡缓存例子
			// Drawable drawable =
			// ImageCacheTool.loadImageFromUrl("http://img9.91huo.cn/sj/images/index/v3/login_pic_1_1.jpg");
			localObject = new TutorialList(this);
			break;

		// 专家
		case CoachSiteMainActivity.EXPERT_VIEW:
			// localObject = new CommonAppView(this);
			localObject = new MyExpertView(this);
			comAppExpert = (MyExpertView)localObject;
			break;

		// 我的
		case CoachSiteMainActivity.MANAGE_VIEW:
		case CoachSiteMainActivity.MORE_VIEW:
		case CoachSiteMainActivity.CLIENT_VIEW:
			if (isExpert) {
				if (paramInt == 6) {
					int args = getIntent().getIntExtra("args", -1);
					localObject = new ManageMainView(this, args + paramInt);
					comAppOwer = localObject;
				} else if (paramInt == 5) {
					int args = getIntent().getIntExtra("args", -1);
					localObject = new CustomMainView(this, args + paramInt);
					comAppCustom = localObject;
					CustomMainView cusView = (CustomMainView) localObject;
					if (cusView != null) {
						//cusView.onCompleted(true, "");
						// cusView.enterMessageView("15396205613", "震川");
					}
				}
			} else {
				int args = getIntent().getIntExtra("args", -1);
				localObject = new OwerMainView(this, args + paramInt);
				if (paramInt == 5) {
					comAppOwer = localObject;
				}
			}

			break;

		default:
			localObject = null;
		}

		return localObject;

	}

	private void onBeforeShowView(int paramInt) {
		int i = getCurrentTabMark();
		setButtonSelected(i, false);
		setButtonSelected(paramInt, true);
	}

	private void onAfterShowView(int paramInt) {
		if(paramInt == 5)
		{
			CustomMainView cusView = (CustomMainView) comAppCustom;
			if (cusView != null) {
				cusView.loadInfo(R.id.ll_custom_personal_info);
			}
		}
	}

	public CommonAppView getCurrentTab() {

		CommonAppView localView = null;

		if (contentFrame != null && contentFrame.getChildCount() > 0) {
			Object objLocalView = contentFrame.getChildAt(0);

			if (objLocalView instanceof CommonAppView)
				localView = (CommonAppView) objLocalView;
		}
		return localView;
	}

	public int getCurrentTabMark() {
		return this.currentMark;
	}

	public void setButtonTextColor(RelativeLayout actionView,
			boolean paramBoolean) {

		if (actionView != null) {

			for (int i = 0; i < actionView.getChildCount(); i++) {
				View child = actionView.getChildAt(i);
				if ((child instanceof TextView)
						&& child.getBackground() == null) {
					TextView actionChild = (TextView) child;
					if (paramBoolean) {
						actionChild.setTextColor(Color.WHITE);
					} else {
						actionChild.setTextColor(Color.BLACK);
					}
				}
			}
		}
	}

	private void setButtonSelected(int paramInt, boolean paramBoolean) {

		switch (paramInt) {
		case CoachSiteMainActivity.MAIN_VIEW:
			this.mainPageButton.setSelected(paramBoolean);
			setButtonTextColor(mainPageButton, paramBoolean);
			break;

		case CoachSiteMainActivity.APP_VIEW:
			this.appButton.setSelected(paramBoolean);
			setButtonTextColor(appButton, paramBoolean);
			break;

		case CoachSiteMainActivity.TUTORIAL_VIEW:
			this.tutorialButton.setSelected(paramBoolean);
			setButtonTextColor(tutorialButton, paramBoolean);
			break;

		case CoachSiteMainActivity.EXPERT_VIEW:
			this.expertButton.setSelected(paramBoolean);
			setButtonTextColor(expertButton, paramBoolean);
			break;

		case CoachSiteMainActivity.MANAGE_VIEW:
			this.manageButton.setSelected(paramBoolean);
			setButtonTextColor(manageButton, paramBoolean);
			break;

		case CoachSiteMainActivity.CLIENT_VIEW:
			this.clientButton.setSelected(paramBoolean);
			setButtonTextColor(clientButton, paramBoolean);
			break;

		case CoachSiteMainActivity.MORE_VIEW:
			this.moreButton.setSelected(paramBoolean);
			setButtonTextColor(moreButton, paramBoolean);
			break;

		default:
			this.mainPageButton.setSelected(paramBoolean);
			setButtonTextColor(mainPageButton, paramBoolean);
		}
	}

	public void onClick(View paramView) {
		final int i = getShowViewMark(paramView);
		if (i != defaultMark) {
			if (i == EXPERT_VIEW || i == MANAGE_VIEW || i == CLIENT_VIEW) {
				if (!LoginHelper.requireLogin(this))
					return;
			}
			showChoosedView(i);
		}
	}

	private int getShowViewMark(View paramView) {

		int i = 1;
		switch (paramView.getId()) {

		case R.id.mainPageButton:
			i = CoachSiteMainActivity.MAIN_VIEW;
			break;

		case R.id.appButton:
			i = CoachSiteMainActivity.APP_VIEW;
			break;

		case R.id.tutorialButton:
			i = CoachSiteMainActivity.TUTORIAL_VIEW;
			break;

		case R.id.expertButton:
			i = CoachSiteMainActivity.EXPERT_VIEW;
			break;

		case R.id.manageButton:
			i = CoachSiteMainActivity.MANAGE_VIEW;
			break;

		case R.id.clientButton:
			i = CoachSiteMainActivity.CLIENT_VIEW;
			break;

		case R.id.moreButton:
			i = CoachSiteMainActivity.MORE_VIEW;
			break;

		default:
			i = CoachSiteMainActivity.MAIN_VIEW;
		}

		return i;
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		View currentView = getCurrentTab();
		if (currentView != null
				&& ((CommonAppView) currentView).doContextItemSelected(item)) {
			return true;
		}
		return super.onContextItemSelected(item);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			View currentView = getCurrentTab();
			if (currentView != null && ((CommonAppView) currentView).goBack()) {
				// && ((CommonAppView) currentView).flushView()) {
				return true;
			}
			if (isExit == false) {
				isExit = true;
				Toast.makeText(this, R.string.main_tip_back_exit,
						Toast.LENGTH_SHORT).show();
				if (!hasTask) {
					tExit.schedule(exitTask, 2000);
				}
				return true;
			} else {
				// TODO 检测相关需要保存的资源
				finish();
				// System.exit(0);
				android.os.Process.killProcess(android.os.Process.myPid());
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private class SoftDownloadProgressReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

		}
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			String keyword = intent.getStringExtra("keyword");

			if (action.equals(ACTION_SEARCH_NAME)) {
				try {
					Integer localInteger = Integer
							.valueOf(CoachSiteMainActivity.APP_VIEW);
					SoftMgrTabLazyView softMgrTabLazyView = (SoftMgrTabLazyView) viewCache
							.get(localInteger);

					if (softMgrTabLazyView == null) {
						softMgrTabLazyView = new SoftMgrTabLazyView(
								CoachSiteMainActivity.this, 2);
						viewCache.put(localInteger, softMgrTabLazyView);
					}

					showChoosedView(CoachSiteMainActivity.APP_VIEW);
					if (softMgrTabLazyView != null) {
						softMgrTabLazyView.vp.snapToScreen(2);
						softMgrTabLazyView.softMgrSearchView.searchNameType = true;
						softMgrTabLazyView.softMgrSearchView.mEditKeyword
								.setText(keyword);
						softMgrTabLazyView.softMgrSearchView
								.searchByKeyWord(keyword);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	};

	class NewMessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			int newMessageCount = intent.getIntExtra("newMessageCount", 0);
			String users = intent.getStringExtra("newMessageUser");
			Message updateMessage = new Message();
			updateMessage.what = 1;
			updateMessage.arg1 = newMessageCount;
			updateMessage.obj = users;
			handler.sendMessage(updateMessage);
		}
	}
}